// Copyright 2006 Marcus Schulte
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Copyright 2006 Marcus Schulte
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.bookie.stateful;

import java.util.Map;

import org.apache.tapestry.engine.state.StateObjectFactory;
import org.apache.tapestry.engine.state.StateObjectPersistenceManager;

public class ConversationScopePersistenceManager implements StateObjectPersistenceManager {

	private String applicationId;
	private ConversationManager conversationMgr;
	
	public ConversationScopePersistenceManager( ConversationManager mgr) {
		conversationMgr = mgr;
	}
	
	public boolean exists(String objectName) {
		// TODO Auto-generated method stub
		return false;
	}

	public Object get(String objectName, StateObjectFactory factory) {
		String key = buildKey(objectName);
        
		Map<String, Object> map = conversationMgr.getCurrentConversation();

        Object result = map.get(key);
        if (result == null)
        {
            result = factory.createStateObject();
            map.put(key, result);
        }

        return result;
	}

	public void store(String objectName, Object stateObject) {
		
		conversationMgr.getCurrentConversation().put( buildKey(objectName), stateObject );
	}


	 private String buildKey(String objectName) {
	        // For Portlets, the application id is going to be somewhat redundant, since
	        // the Portlet API keeps portlets seperate anyway.

	        return "state:" + applicationId + ":" + objectName;
	  }
	 
	 public void setApplicationId( String id ){
		 applicationId = id;
	 }
}
